package com.icehand.utils.byte2;

import java.io.*;

/**
 * 字节转换类
 * Created by icehand on 2017/5/3.
 */
public class ByteUtils {
	private final static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	/**
	 * 计算一个byte返回数字跟字符串
	 * @param bByte 字节
	 * @return String
	 */
	public static String byte2String(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return strDigits[iD1] + strDigits[iD2];
	}

	/**
	 * 返回数字
	 * @param bByte 字节
	 * @return String
	 */
	public static String byte2Number(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		return String.valueOf(iRet);
	}

	/**
	 * 转换字节数组为16进制字符串
	 * @param bByte      字节数组
	 * @return HexString
	 */
	public static String bytes2HexString(byte[] bByte) {
		StringBuilder sBuffer = new StringBuilder();
		for (byte item : bByte) {
			sBuffer.append(byte2String(item));
		}
		return sBuffer.toString();
	}

	/**
	 * 字节数组转为对象
	 * @param bytes 字节数组
	 * @return Object
	 * @throws IOException io
	 * @throws ClassNotFoundException classNotFound
	 */
	public static Object bytes2Object(byte[] bytes) throws IOException, ClassNotFoundException {
		ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
		ObjectInputStream oi = new ObjectInputStream(bi);
		Object obj = oi.readObject();
		bi.close();
		oi.close();
		return obj;
	}

	/**
	 * 对象转为字节数组
	 * @param obj object
	 * @return bytes
	 * @throws IOException io
	 */
	public static byte[] object2Bytes(Object obj) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(obj);
		oos.flush();
		byte[] bytes = bos.toByteArray();
		oos.close();
		bos.close();
		return bytes;
	}

}
